<template>
  <div>
    <t-card class="list-card-container" :bordered="false">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <!--          <t-button @click="formDialogVisible = true">新建参数</t-button>-->
        </div>
        <div class="search-input">
          <t-button theme="default" @click="refreshTable">刷新</t-button>
        </div>
      </t-row>

      <dialog-form v-model:visible="formDialogVisible" :data="formData" @refresh-table="refreshTable" />

      <t-table
        :data="data"
        :columns="columns"
        :row-key="rowKey"
        vertical-align="top"
        :hover="true"
        :pagination="pagination"
        :loading="dataLoading"
        :header-affixed-top="headerAffixedTop"
        @page-change="rehandlePageChange"
      >
        <template #identitySwitch="{ row }">
          {{ row.identitySwitch ? '是' : '否' }}
        </template>
        <template #wechatUserIdcardPortraitImages="{ row }">
          <template v-if="row.wechatUserIdcardPortraitImages && row.wechatUserIdcardPortraitImages.length > 0">
            <t-image-viewer :images="row.wechatUserIdcardPortraitImages.map((o:any) => `${o.filePath}`)">
              <template #trigger="{ open }">
                <t-space>
                  <t-link theme="primary" @click="open">查看</t-link>
                </t-space>
              </template>
            </t-image-viewer>
          </template>
        </template>
        <template #wechatUserWorkCardImages="{ row }">
          <template v-if="row.wechatUserWorkCardImages && row.wechatUserWorkCardImages.length > 0">
            <t-image-viewer :images="row.wechatUserWorkCardImages.map((o:any) => `${o.filePath}`)">
              <template #trigger="{ open }">
                <t-space>
                  <t-link theme="primary" @click="open">查看</t-link>
                </t-space>
              </template>
            </t-image-viewer>
          </template>
        </template>
        <template #wechatUserBusinessLicenseImages="{ row }">
          <template v-if="row.wechatUserBusinessLicenseImages && row.wechatUserBusinessLicenseImages.length > 0">
            <t-image-viewer :images="row.wechatUserBusinessLicenseImages.map((o:any) => `${o.filePath}`)">
              <template #trigger="{ open }">
                <t-space>
                  <t-link theme="primary" @click="open">查看</t-link>
                </t-space>
              </template>
            </t-image-viewer>
          </template>
        </template>
        <template #wechatUserStockProveImages="{ row }">
          <template v-if="row.wechatUserStockProveImages && row.wechatUserStockProveImages.length > 0">
            <t-image-viewer :images="row.wechatUserStockProveImages.map((o:any) => `${o.filePath}`)">
              <template #trigger="{ open }">
                <t-space>
                  <t-link theme="primary" @click="open">查看</t-link>
                </t-space>
              </template>
            </t-image-viewer>
          </template>
        </template>
        <template #createTime="{ row }">
          {{ `${dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')}(${row.createUserName})` }}
        </template>
        <template #updateTime="{ row }">
          <template v-if="row.updateTime">
            {{ `${dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss')}(${row.updateUserName})` }}
          </template>
        </template>
        <template #op="slotProps">
          <t-space>
            <t-link theme="primary" @click="handleClickDetail(slotProps)">编辑</t-link>
            <!--              <t-link theme="danger" @click="handleClickDelete(slotProps)">删除</t-link>-->
          </t-space>
        </template>
      </t-table>
    </t-card>

    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选系统配置？"
      :body="confirmBody"
      :on-cancel="onCancel"
      @confirm="onConfirmDelete"
    />
  </div>
</template>

<script lang="tsx">
export default {
  name: 'UserIdentityList',
};
</script>

<script setup lang="tsx">
import dayjs from 'dayjs';
import { MessagePlugin, PrimaryTableCol } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';

import { post } from '@/api/common';
import { loadTableList } from '@/api/list';
import { prefix } from '@/config/global';
import { useSettingStore } from '@/store';

import type { FormData } from './components/DialogForm.vue';
import DialogForm from './components/DialogForm.vue';

const store = useSettingStore();

const columns: PrimaryTableCol[] = [
  { title: '认证ID', colKey: 'identityId' },
  { title: '真实姓名', colKey: 'identityRealName' },
  { title: '认证类型', colKey: 'identityTypeLabel' },
  { title: '公司名称', colKey: 'identityCompanyName' },
  { title: '状态', colKey: 'identityStatusLabel' },
  { title: '主认证', colKey: 'identitySwitch' },
  { title: '身份证', colKey: 'wechatUserIdcardPortraitImages' },
  { title: '工牌', colKey: 'wechatUserWorkCardImages' },
  { title: '营业执照', colKey: 'wechatUserBusinessLicenseImages' },
  { title: '持股证明', colKey: 'wechatUserStockProveImages' },
  { title: '创建', colKey: 'createTime' },
  { title: '更新', colKey: 'updateTime' },
  { title: '操作', colKey: 'op' },
];

const INITIAL_DATA: FormData = {
  identityId: null,
  identityRealName: '',
  identityStatusValue: null,
  identityStatusLabel: '',
  createUserId: null,
};

const formData = ref({ ...INITIAL_DATA });

const formDialogVisible = ref(false);

const data = ref([]);
const pagination = ref({
  defaultPageSize: 20,
  total: -1,
  defaultCurrent: 1,
});

// const searchValue = ref('');

const dataLoading = ref(false);

const refreshTable = async () => {
  pagination.value.total = -1;
  await fetchData();
};

const fetchData = async () => {
  dataLoading.value = true;
  try {
    const { list, total } = await loadTableList('/wechatUser/identity/table', {
      // @ts-ignore
      current: pagination.value.current || pagination.value.defaultCurrent,
      // @ts-ignore
      pageSize: pagination.value.pageSize || pagination.value.defaultPageSize,
      total: pagination.value.total,
    });
    data.value = list;
    pagination.value = {
      ...pagination.value,
      total,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const deleteIdx = ref(-1);
const confirmBody = computed(() => {
  if (deleteIdx.value > -1) {
    const { configKey } = data.value[deleteIdx.value];
    return `删除后， ${configKey} 的所有配置将被清空，且无法恢复`;
  }
  return '';
});

onMounted(() => {
  fetchData();
});

const confirmVisible = ref(false);

const resetIdx = () => {
  deleteIdx.value = -1;
};

const onConfirmDelete = async () => {
  // 真实业务请发起请求
  await post(`/wechatUser/remove/${data.value[deleteIdx.value].configId}`, {});
  //
  data.value.splice(deleteIdx.value, 1);
  pagination.value.total = data.value.length;
  confirmVisible.value = false;
  MessagePlugin.success('删除成功');
  resetIdx();
  await refreshTable();
};

const onCancel = () => {
  resetIdx();
};

const rowKey = 'configId';

const rehandlePageChange = (curr: unknown, pageInfo: unknown) => {
  console.log('分页变化', curr, pageInfo);
  // @ts-ignore
  pagination.value.current = curr.current;
  // @ts-ignore
  pagination.value.pageSize = curr.pageSize;
  fetchData();
};

const handleClickDetail = (data: any) => {
  // router.push('/detail/base');
  console.log(`row`, data.row);
  formData.value = { ...data.row };
  formDialogVisible.value = true;
};

const handleClickDelete = (row: { rowIndex: any }) => {
  deleteIdx.value = row.rowIndex;
  confirmVisible.value = true;
};

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any,
);
</script>

<style lang="less" scoped>
.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}

.list-card-container {
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);

  :deep(.t-card__body) {
    padding: 0;
  }
}

.left-operation-container {
  display: flex;
  align-items: center;
  margin-bottom: var(--td-comp-margin-xxl);

  .selected-count {
    display: inline-block;
    margin-left: var(--td-comp-margin-l);
    color: var(--td-text-color-secondary);
  }
}

.search-input {
  //width: 360px;
}
</style>
